<template>
  <div class="lc_wrap">
    <el-row class="trendanalysis">

      <!-- 左侧树 -->
      <el-col :span="leftWidth">
        <div class="box treeBox">
          <basic-container>
            <lcTree @ready="ready" :deviceType="2"></lcTree>
          </basic-container>
        </div>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :span="rightWidth" class="table-wrapper" style="position: relative">
        <overlay @changeTreeBox="changeTreeBox"></overlay>
        <basic-container>
          <div class="search-tools">
            <div class="search-left">

              <!-- 月 （dateType==4）-->
              <div>
                <el-date-picker 
                  v-model="dateTime" 
                  type="date" 
                  size="small" 
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOption" 
                  placeholder="选择日期" 
                  :clearable='false'>
                </el-date-picker>
              </div>

              <!-- 化合物类型 -->
              <label class="search_label">化合物类型</label>
              <el-select size="small" v-model="vocType">
                <el-option 
                  v-for="(item, index) in vocTypeOption" 
                  :key="index" 
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>

              <!-- 化合物名称 -->
              <label class="search_label">名称</label>
              <el-select id="voc_name_select" size="small" multiple multiple-limit=5 filterable v-model="vocNames">
                <el-option 
                  v-for="item in vocNameOption" 
                  :key="item.value" 
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>

              <el-button class="search_btn" type="primary" size="small" icon="el-icon-search" @click="searchBtn">搜 索</el-button>
            </div>
          </div>
          <noData v-if="isEmpty"></noData>
          <div v-else style="height:92%;">
            <e-chart autoresize :options="chartOptions" style="height:100%;"></e-chart>
          </div>
        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getFactors, getLine} from "@/api/evoc/trendanalysis";
import {mapGetters} from "vuex";
import {dateFormat} from "@/util/date";
import lcTree from "@/components/common/tree.vue";
import noData from "@/components/common/noData";
import overlay from "@/components/common/overlay.vue";

export default {
  components: {
    lcTree,
    noData,
    overlay
  },
  data() {
    let _this = this
    return {
      vocType: "",
      vocTypeOption: [],
      vocNames: [],
      vocNameOption: [],
      groupedFactor: [],
      isEmpty: true,
      chartOptions: {},
      leftWidth: this.$leftWidth,
      rightWidth: this.$rightWidth,
      data: [],
      dateTime: dateFormat(new Date(), 'yyyy-MM-dd'), // 默认显示的日期
      pickerOption: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
      deptInfoId: '',
      geneList: [],
      gene: '',
      selectFactor: {},
      unit: '',
      interval: 59,
      kChartData: {xArray: [], yArray: []},
      monthData: [],
      chartData: {}
    };
  },
  computed: {
    ...mapGetters(["permission"])
  },
  watch: {
    // 化合物类型
    vocType() {
      if (this.vocType) {
        this.vocNameOption = [];
        this.vocNames = [];
        this.groupedFactor.forEach(item => {
          if (item.typeId === this.vocType) {
            this.vocNameOption = item.children;
          }
        });
        if(this.vocNameOption.length > 0) {
          this.vocNames.push(this.vocNameOption[0].value);
        }
      }
    },

    // 化合物名称
    vocNames() {
      var selectEle = document.getElementById("voc_name_select");
      if (this.vocNames.length > 1) {
        var labels = "";
        this.vocNameOption.forEach(item => {
          this.vocNames.forEach(el => {
            if(el === item.value) {
              labels = labels + item.label;
            }
          });
        });
        var totalWidth = labels.length * 12 + this.vocNames.length * 25 + 80;
        if(totalWidth > 194) {
          selectEle.style.width = totalWidth + "px";
        }
      } else {
        selectEle.style.width = "194px";
      }
    }
  },
  methods: {
    // 左侧树加载完毕时间
    ready(val) {
      this.deptInfoId = val.key;
      this.dateTime = dateFormat(new Date(), 'yyyy-MM-dd');
      this.onLoad();
    },

    // 加载页面
    onLoad() {
      getFactors().then(res => {
        if(res.data.success !== true) {
          return;
        }
        this.groupedFactor = res.data.data;
        this.vocTypeOption = [];
        this.vocNameOption = [];
        this.vocNames = [];

        // 所有化合物类型
        this.groupedFactor.forEach(item => {
          this.vocTypeOption.push({
            label: item.typeName,
            value: item.typeId
          });
        });

        // 默认选中第一个化合物类型
        this.vocType = this.vocTypeOption.length > 0 ? this.vocTypeOption[0].value : "";

        // 化合物名称
        this.groupedFactor.forEach(item => {
          if(item.typeId === this.vocType) {
            this.vocNameOption = item.children;
          }
        });

        // 默认选中第一个化合物名称
        if(this.vocNameOption.length > 0) {
          this.vocNames.push(this.vocNameOption[0].value);
        }
        
      }).then(() => {
        this.getLineChart();
      });
    },

    // 获取折线图数据
    getLineChart() {
      if(this.vocNames.length === 0) {
        this.$message.warning('请先选择化合物名称');
        return;
      }
      var pointId = this.deptInfoId;
      var time = this.dateTime;
      var typeId = this.vocType || "";
      var factorIds = JSON.stringify(this.vocNames);
      getLine(pointId, time, typeId, factorIds).then(res => {
        if(res.data.success !== true) {
          return;
        }
        var resData = res.data.data;
        this.isEmpty = false;

        // 获取各因子对应的单位
        var factorUnit = {};
        resData.forEach(item =>{
          factorUnit[item.factorName] = item.unit;
        });

        this.chartOptions = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              var html = params[0].name + '<br>';
              params.forEach(item => {
                html = html + item.marker + item.seriesName + ": " + item.data + factorUnit[item.seriesName] + '<br>';
              });
              return html.substring(0 , html.length - 4);
            }
          },
          legend: {},
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category',
            data: [],
            axisLabel: {
              interval: this.interval,
              color: '#ccc'
            },
            axisLine: {
              lineStyle: {
                color: '#505b83'
              }
            },
            axisTick: false
          }],
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value}',
              color: '#333',
            },
            axisLine: {
              lineStyle: {
                color: '#505b83'
              }
            },
            axisTick: false,
            splitLine: {
              show: true,
              lineStyle: {
                color: '#374062',
                type: 'dashed'
              }
            }
          },
          series: []
        }

        this.chartOptions.xAxis[0].data = resData.length > 0 ? resData[0].xarray : [];
        resData.map((item, ind) => {
          this.chartOptions.series.push({
            data: item.yarray,
            type: 'line',
            smooth: 0.5,
            name: item.factorName
          })
        });
      });
    },

    // 改变tree box
    changeTreeBox() {
      this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
      this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
    },

    // 点击搜索按钮
    searchBtn() {
      this.getLineChart();
    }
  }
};
</script>



<style lang="scss" scoped>
.empty {
  position: absolute;
  left: 0;
  top: 20%;
  color: #ccc;
  right: 0;
  bottom: 20%;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #909399;
}

.map {
  width: 100%;
  height: 500px;
}

.box {
  height: 100%;
  margin-bottom: 0;
}

.search-left {
  display: flex;
  height: 32px;
  align-items: center;
}

.el-row {
  height: calc(100% - 20px);
}

.el-col {
  height: 100%;
  overflow: auto;
}

.search-tools {
  height: 50px;
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
}

.search-right {
  display: flex;
}

.search-tabs {
  height: 33px;
  display: flex;
  align-items: center;
  margin-right: 40px;
}

.overlay {
  position: absolute;
  width: 200px;
  height: calc(100% - 35px);
  opacity: 0;
  display: flex;
  align-items: center;
  padding-left: 6px;

  .tree-tool {
    height: 34px;
    width: 18px;
    background: #fff;
    box-shadow: 2px 1px 4px #ccc;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    cursor: pointer;
    display: flex;
    padding: 6px 0;
    z-index: 9999;

    .tool-line {
      margin-left: 3px;
      height: 100%;
      border-left: 1px solid #ddd;
    }
  }
}

.overlay:hover {
  opacity: 1;
}

.el-divider{
  margin: 20px 0px !important;
}

.search_label{
  font-size: 14px;
  margin: 0px 10px;
}

.search_btn{
  margin-left: 10px;
}
</style>
